<?php

namespace app\service\upload;

use app\model\UploadFileModel;
use Exception;
use Tinywan\Storage\Storage;

class UploadService
{

    public function upload($files){

        $upload_info = get_option_value('upload_config');

        $type = $upload_info['type'] ?? 0;

        //允许的文件扩展名
        $upload_info_extensions = explode(",",trim($upload_info['extensions'],","));

        //最大上传大小
        $maxsize = bcmul($upload_info['maxsize'],(1024*1024),0);

        //验证文件类型 、 文件大小等
        foreach ($files as $key => $spl_file) {

            //字节/1024/1024 = Mb
            
            if(!$spl_file->isValid()){
                throw new Exception($spl_file->getUploadName().'已失效');
                //return error($spl_file->getUploadName().'已失效');
            }

            if(!in_array($spl_file->getUploadExtension(),$upload_info_extensions)){
                throw new Exception($spl_file->getUploadExtension().'文件不允许上传');
                //return error($spl_file->getUploadExtension().'文件不允许上传');
            }

            if($spl_file->getSize() > $maxsize){
                throw new Exception($spl_file->getUploadName().'大小超出上传限制');
                //return error($spl_file->getUploadName().'大小超出上传限制');
            }

            // var_export($spl_file->isValid()); // 文件是否有效，例如ture|false
            // var_export($spl_file->getUploadExtension()); // 上传文件后缀名，例如'jpg'
            // var_export($spl_file->getUploadMineType()); // 上传文件mine类型，例如 'image/jpeg'
            // var_export($spl_file->getUploadErrorCode()); // 获取上传错误码，例如 UPLOAD_ERR_NO_TMP_DIR UPLOAD_ERR_NO_FILE UPLOAD_ERR_CANT_WRITE
            // var_export($spl_file->getUploadName()); // 上传文件名，例如 'my-test.jpg'
            // var_export($spl_file->getSize()); // 获得文件大小，例如 13364，单位字节
            // var_export($spl_file->getPath()); // 获得上传的目录，例如 '/tmp'
            // var_export($spl_file->getRealPath()); // 获得临时文件路径，例如 `/tmp/workerman.upload.SRliMu`        
        }

        try{
            switch($type){
                case 0:
                    $store = "local";
                    break;
                case 1:
                    $store = "oss";
                    break;
                case 2:
                    $store = "qiniu";
                    break;
                case 2:
                    $store = "cos";
                    break;
            }
            Storage::config($store);
            $res = Storage::uploadFile();

        }catch(\Throwable $e){
            throw new Exception('上传失败'.$e->getMessage());
        }

        //添加文件上传记录
        foreach($res as $k=>$v){
            UploadFileModel::upload($v);
            //隐藏完整路径
            unset($res[$k]['save_path']);
            $res[$k]['http_url'] = get_image_url($v['url']);
        }

        return $res;
    }

}